package com.luke.exercise.concurrent;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

public class JoinForkDemo extends RecursiveTask<Integer>{

    private static final long serialVersionUID = 1L;

    private static final int THRESHOLD = 10;
    
    private int start;
    
    private int end;
    
    public JoinForkDemo(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        if( (end-start) < THRESHOLD) {
            for(int i=start ; i<=end ; i++) {
                sum += i;
            }
        } else {
            int middle = (start + end) >>> 1;
            JoinForkDemo left = new JoinForkDemo(start, middle);
            JoinForkDemo right = new JoinForkDemo(middle+1, end);
            left.fork();
            right.fork();
            
            sum = left.join() + right.join();
        }
        return sum;
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        Future<Integer> result = forkJoinPool.submit(new JoinForkDemo(1, 10000));
        System.out.println(result.get());
    }
}
